<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>
    <body>
        <script>
            /*
            思路：从candidates中寻找目标数，使其总和==target。元素可以任意取。所以每次start无需＋1，可以从自身开始
            遍历范围。但是解集不能有重复，所以推送到res的时候，必须进行去重。去重注意，必须重新拷贝一份path数组，不然会有问题
            因为[1,2,1]中选取target=3 [1,2]和[2,1]算两种组合

            */
            var combinationSum = function (candidates, target) {
                let res = []
                let map = new Map()
                function backTracking(path, start, sum) {
                    if (sum > target) return
                    if (sum == target) {
                        let str = [...path].sort((a, b) => a - b).join('')
                        if (map.has(str)) return
                        return res.push([...path])
                    }
                    for (let i = start; i < candidates.length; i++) {
                        path.push(candidates[i])
                        backTracking(path, i, sum + candidates[i])
                        path.pop()
                    }
                }
                backTracking([], 0, 0)
                return res
            }
        </script>
    </body>
</html>
